﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Sunboxsoft.WinForm;
using WebRef = Sunboxsoft.ASMS.Client.Domain.WebRef;
using Service = Sunboxsoft.ASMS.Client.Domain.Service;
using Sunboxsoft.Common;
using Sunboxsoft.ASMS.Client.UI.Properties;
namespace Sunboxsoft.ASMS.Client.UI.Dispatching
{
    /// <summary>
    /// 领料退料
    /// </summary>
    public partial class MaintenanceBillMaterialView : UserControl, IView
    {
        #region Property
        /// <summary>
        /// 维修单号
        /// </summary>
        Guid Id;
        /// <summary>
        /// 维修单详细信息
        /// </summary>
        WebRef.MaintenanceBillDetail billDetail = null;
        Promise _promise = new Promise();
        #endregion

        #region IView 成员
        public void RegisterAction(ActionNodeCollection collection)
        {
            collection.AddAction(new ActionNode("back", Resources.isBack, "返回", btnBack_Click))
                .AddAction(new ActionNode("getMaterial", Resources.isGetMaterial, "领料", btnGetMaterial_Click) { IsShow = false })
                .AddAction(new ActionNode("returnMaterial", Resources.isReset, "退料", btnReturnMaterial_Click) { IsShow = false })
                .AddAction(new ActionNode("dispact", Resources.isDispatchingOrderList, "派工施工", btnDispict_Click) { IsShow = false })
                .AddAction(new ActionNode("checked", Resources.isSettling, "订单结算", btnSettleMent_Click) { IsShow = false })
              .AddAction(new ActionNode("refresh", Resources.isRefresh, "刷新", btnRefresh_Click));
        }
        public void Resume(ViewResumeArgs args)
        {

        }
        public void Active(ViewActiveArgs args)
        {
            _promise
                .Then(() =>
                {
                    repositoryItemSearchLookUpEditHandler.BindVStaffPosition(this, _promise, Domain.Constant.StaffPosts.SalesManager);
                })
                .Then(BindData).Run();
        }
        public ViewHeader GetHeader()
        {
            return new ViewHeader("服务单领料");
        }
        #endregion

        #region Method
        /// <summary>
        /// 构造方法
        /// </summary>
        public MaintenanceBillMaterialView()
        {
            InitializeComponent();
        }
        public MaintenanceBillMaterialView(Guid Id)
        {
            InitializeComponent();
            this.Id = Id;
        }
        public MaintenanceBillMaterialView(WebRef.MaintenanceBillDetail billDetail)
        {
            InitializeComponent();
            this.billDetail = billDetail;
        }
        /// <summary>
        /// 数据绑定
        /// </summary>
        private void BindData()
        {
            if (billDetail == null)
            {
                this.ShowMask("loading...");
                UIContext.Current.InvokeAsync(() =>
                {
                    SingleResult<WebRef.MaintenanceBillDetail> result = new Service.GetService().GetMaintenanceBill(Id);
                    this.BeginInvoke(new Action(() =>
                    {
                        this.HideMask();
                        if (result.IsSuccess)
                        {
                            billDetail = result.Data;
                            ShowActionByStatus();
                            BindBillDetail();
                            _promise.Resolve();
                        }
                        else
                        {
                            UIContext.Current.ViewManager.ShowError(result.Message);
                            _promise.Reject();
                        }
                    }));
                });
            }
            else
            {
                this.BeginInvoke(new Action(() =>
                {
                    Id = billDetail.Bill.Id;
                    ShowActionByStatus();
                    BindBillDetail();
                    _promise.Resolve();
                }));
            }
        }
        /// <summary>
        /// 根据维修单状态控制按钮显示
        /// </summary>
        private void ShowActionByStatus()
        {
            switch (billDetail.Bill.Status)
            {
                case Domain.Constant.MaintenanceBillStatus.WaitDispatching:
                case Domain.Constant.MaintenanceBillStatus.Working:
                    {
                        if (billDetail.Bill.MaterialStatus == Domain.Constant.MaintenanceBillStatus.MaterialStatus.Wait)
                        {
                            this.ShowAction("getMaterial", true);
                        }
                        else
                        {
                            this.ShowAction("getMaterial", false);
                        }
                        if (billDetail.Bill.MaterialStatus == Domain.Constant.MaintenanceBillMaterialStatus.Finished)
                        {
                            this.ShowAction("returnMaterial", true);
                        }
                        else
                        {
                            this.ShowAction("returnMaterial", false);
                        }
                        if (billDetail.Bill.ServiceItemCount > 0)
                        {
                            this.ShowAction("dispact", true);
                        }
                        else
                        {
                            this.ShowAction("dispact", false);
                        }
                        break;
                    }
                case Domain.Constant.MaintenanceBillStatus.WaitSettling:
                    this.ShowAction("checked", true);
                    break;
            }
        }
        /// <summary>
        /// 数据初始化
        /// </summary>
        private void BindBillDetail()
        {
            this.txtCode.Text = billDetail.Bill.Number;
            this.ctltxtSalesManagerName.Text = billDetail.Bill.SalesManagerName;
            this.txtCreateTime.Text = billDetail.Bill.CreatedTime.ToString();
            this.txtCustomerInfo.Text = string.Format("{0}-{1}", billDetail.Bill.CustomerName, billDetail.Bill.CustomerTelephone);
            this.txtCarInfo.Text = billDetail.Bill.LPN;//string.Format("{0}-{1}-{2}", billDetail.Bill.LPN, billDetail.Bill.VIN, billDetail.Bill.EIN);
            this.txtMemo.Text = billDetail.Bill.Memo;

            for (int i = 0; i < billDetail.MaterialList.Length; i++)
            {
                billDetail.MaterialList[i].WarehouseId = billDetail.MaterialList[i].ActualWarehouseId != null ? billDetail.MaterialList[i].ActualWarehouseId : billDetail.MaterialList[i].WarehouseId;
            }
            this.GCGoodsData.DataSource = null;
            this.GVGoodsData.FocusedRowHandle = -1;
            this.GCGoodsData.DataSource = billDetail.MaterialList;
        }
        /// <summary>
        /// 根据物料ID绑定仓库及库存数据
        /// </summary>
        private void BindWareHouseAndStockByMaterialId(Guid materialId)
        {
            this.ShowMask("loading...");
            UIContext.Current.InvokeAsync(() =>
               {
                   ListResult<WebRef.VMaterialWithStock> result = new Service.QueryService().QueryStockMaterialPagedList(
                    ModuleContext.Current.BusinessId.Value,
                    ModuleContext.Current.StationId.Value,
                    materialId);
                   this.BeginInvoke(new Action(() =>
                   {
                       if (result.IsSuccess)
                       {
                           this.repositoryItemSearchLookUpEditWareHouse.DataSource = result.Data.Items;
                           this.repositoryItemSearchLookUpEditWareHouse.DisplayMember = "WarehouseName";
                           this.repositoryItemSearchLookUpEditWareHouse.ValueMember = "WarehouseId";
                           _promise.Resolve();
                       }
                       else
                       {
                           UIContext.Current.ViewManager.ShowError(result.Message);
                           _promise.Reject();
                       }
                       this.HideMask();
                   }));
               });
        }
        /// <summary>
        /// 创建出库单
        /// </summary>
        /// <param name="item"></param>
        private void CreateMaterialRequisitionBill(WebRef.VMaintenanceBillMaterial item)
        {
            WebRef.EMaterialRequisitionBill bill = new WebRef.EMaterialRequisitionBill();
            bill.MaintenanceBillId = billDetail.Bill.Id;
            bill.MaintenanceBillMaterialId = item.Id;
            bill.MaterialId = item.MaterialId;
            bill.WarehouseId = new Guid(item.WarehouseId.ToString());
            if (item.ActualHandlerId != null)
            {
                bill.Handler = new Guid(item.ActualHandlerId.ToString());
            }
            bill.Count = item.Count;

            this.ShowMask("loading...");
            UIContext.Current.InvokeAsync(() =>
            {
                ServiceResult result = new Service.CreateService().CreateMaterialRequisitionBill(bill);
                this.BeginInvoke(new Action(() =>
                {
                    this.HideMask();
                    if (result.IsSuccess)
                    {
                        this.btnRefresh_Click(null, null);
                        _promise.Resolve();
                    }
                    else
                    {
                        UIContext.Current.ViewManager.ShowError(result.Message);
                        _promise.Reject();
                    }
                }));
            });
        }
        #endregion

        #region Action
        /// <summary>
        /// 返回
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBack_Click(object sender, object e)
        {
            UIContext.Current.ViewManager.CloseView(true, null);
        }
        /// <summary>
        /// 刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRefresh_Click(object sender, object e)
        {
            billDetail = null;
            BindData();
        }
        /// <summary>
        /// 领料
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGetMaterial_Click(object sender, object e)
        {
            if (this.GVGoodsData.FocusedRowHandle > -1)
            {
                WebRef.VMaintenanceBillMaterial item = this.GVGoodsData.GetRow(this.GVGoodsData.FocusedRowHandle) as WebRef.VMaintenanceBillMaterial;
                if (item.WarehouseId == null)
                {
                    UIContext.Current.ViewManager.ShowWarning("请选择出库仓库！");
                }
                else
                {
                    CreateMaterialRequisitionBill(item);
                }
            }
        }
        /// <summary>
        /// 退料
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReturnMaterial_Click(object sender, object e)
        {
            if (this.GVGoodsData.FocusedRowHandle > -1)
            {
                WebRef.VMaintenanceBillMaterial item = this.GVGoodsData.GetRow(this.GVGoodsData.FocusedRowHandle) as WebRef.VMaintenanceBillMaterial;
                if (item.Status == Domain.Constant.MaintenanceBillMaterialStatus.Finished)
                {
                    if (UIContext.Current.ViewManager.ShowQuestion("确定要退料？"))
                    {
                        WebRef.EMaterialReturnedBill returnBill = new WebRef.EMaterialReturnedBill();
                        returnBill.MaintenanceBillId = item.MaintenanceBillId;
                        returnBill.MaintenanceBillMaterialId = item.Id;
                        returnBill.MaterialRequisitionBillId = new Guid(item.MaterialRequisitionBillId.ToString());
                        returnBill.MaterialId = item.MaterialId;
                        returnBill.WarehouseId = new Guid(item.WarehouseId.ToString());
                        returnBill.Handler = new Guid(item.ActualHandlerId.ToString());
                        returnBill.HandledTime = DateTime.Now;
                        returnBill.Count = item.Count;
                        this.ShowMask("loading...");
                        UIContext.Current.InvokeAsync(() =>
                        {
                            ServiceResult result = new Service.CreateService().CreateMaterialReturnedBill(returnBill);
                            this.BeginInvoke(new Action(() =>
                            {
                                this.HideMask();
                                if (result.IsSuccess)
                                {
                                    this.btnRefresh_Click(null, null);
                                    _promise.Resolve();
                                }
                                else
                                {
                                    UIContext.Current.ViewManager.ShowError(result.Message);
                                    _promise.Reject();
                                }
                            }));
                        });
                    }
                }
            }
        }
        /// <summary>
        /// 派工施工
        /// </summary>
        private void btnDispict_Click(object sender, object e)
        {
            UIContext.Current.ViewManager.ReplaceView(new Dispatching.MaintenanceBillDispatchView(billDetail));
        }
        /// <summary>
        /// 根据领料状态显示对应按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GVGoodsData_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (this.GVGoodsData.FocusedRowHandle > -1)
            {
                WebRef.VMaintenanceBillMaterial entity = GVGoodsData.GetRow(GVGoodsData.FocusedRowHandle) as WebRef.VMaintenanceBillMaterial;
                switch (entity.ActualStatus)
                {
                    case null:
                        this.ShowAction("getMaterial", true);
                        this.ShowAction("returnMaterial", false);
                        break;
                    case Domain.Constant.MaterialRequisitionStatus.Finished:
                        this.ShowAction("getMaterial", false);
                        this.ShowAction("returnMaterial", true);
                        break;
                    case Domain.Constant.MaterialRequisitionStatus.Returned:
                        this.ShowAction("getMaterial", false);
                        this.ShowAction("returnMaterial", false);
                        break;
                }
                Guid materialId = entity.MaterialId;
                if (materialId != null)
                {
                    Promise promise = new Promise();
                    promise.Then(() =>
                    {
                        this.BeginInvoke(new Action(() =>
                        {
                            BindWareHouseAndStockByMaterialId(materialId);
                        }));
                    }).Run();
                }
            }
        }
        /// <summary>
        /// 根据出库单状态控制是否可编辑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GVGoodsData_ShowingEditor(object sender, CancelEventArgs e)
        {
            WebRef.VMaintenanceBillMaterial entity = this.GVGoodsData.GetRow(this.GVGoodsData.FocusedRowHandle) as WebRef.VMaintenanceBillMaterial;
            if (entity != null)
            {
                switch (entity.ActualStatus)
                {
                    case null:
                        e.Cancel = false;
                        break;
                    case Domain.Constant.MaterialRequisitionStatus.Finished:
                        e.Cancel = true;
                        break;
                    case Domain.Constant.MaterialRequisitionStatus.Returned:
                        e.Cancel = true;
                        break;
                }
            }
        }
        /// <summary>
        /// 结算
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSettleMent_Click(object sender, object e)
        {
            UIContext.Current.ViewManager.ReplaceView(new Dispatching.MaintenanceBillSettlementView(Id));
        }
        /// <summary>
        /// 解决选择了仓库之后若焦点不离开此单元格，点击领料按钮提示“未选择仓库”问题
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void repositoryItemSearchLookUpEditWareHouse_EditValueChanged(object sender, EventArgs e)
        {
            if (((DevExpress.XtraEditors.SearchLookUpEdit)sender).EditValue != null)
            {
                WebRef.VMaintenanceBillMaterial item = this.GVGoodsData.GetFocusedRow() as WebRef.VMaintenanceBillMaterial;
                item.WarehouseId = new Guid(((DevExpress.XtraEditors.SearchLookUpEdit)sender).EditValue.ToString());
            }
        }
        /// <summary>
        /// 解决选择了领料人之后若焦点不离开此单元格，点击领料按钮不保存领料人问题
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void repositoryItemSearchLookUpEditHandler_EditValueChanged(object sender, EventArgs e)
        {
            if (((DevExpress.XtraEditors.SearchLookUpEdit)sender).EditValue != null)
            {
                WebRef.VMaintenanceBillMaterial item = this.GVGoodsData.GetFocusedRow() as WebRef.VMaintenanceBillMaterial;
                item.ActualHandlerId = new Guid(((DevExpress.XtraEditors.SearchLookUpEdit)sender).EditValue.ToString());
            }
        }
        #endregion
    }
}
